package com.tidc.authorization.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tidc.authorization.mapper.UserMapper;
import com.tidc.authorization.pojo.User;
import com.tidc.authorization.utiles.ApplicationContextProvider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;

/**
 * @ClassNmae UserController
 * @Description TODO
 * @Author 14631
 **/
@CrossOrigin(origins = "*",maxAge = 3600)

@RestController
public class UserController {
	private RestTemplate restTemplate = new RestTemplate();
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private AuthorizationServerTokenServices tokenServices;
	private AccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
	@Autowired
	private ApplicationContextProvider ac;
	@Autowired
	private UserMapper userMapper;
	@GetMapping("/user/info")
	@ResponseBody
	public User checkToken(@RequestParam("access_token") String value) {
		ResourceServerTokenServices resourceServerTokenServices = (ResourceServerTokenServices) this.tokenServices;
		OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
		if (token == null) {
			throw new InvalidTokenException("Token was not recognised");
		} else if (token.isExpired()) {
			throw new InvalidTokenException("Token has expired");
		} else {
			OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());
			Map<String, Object> response = (Map<String, Object>) this.accessTokenConverter.convertAccessToken(token, authentication);
			response.put("active", true);
			String email = (String) response.get("user_name");
			QueryWrapper<User> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("email",email);
			com.tidc.authorization.pojo.User user = userMapper.selectOne(queryWrapper);
			user.setPassword(null);
			return user;
		}
	}


}
